//
//  OAuthViewController.swift
//  SinaMicroblog
//
//  Created by 唐绍禹 on 15/7/30.
//  Copyright © 2015年 唐绍禹. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    private lazy var webView = UIWebView()

    override func loadView() {
        view = webView
        webView.delegate = self
        title  = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    func close() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil);
    
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        let url = NetworkTools.sharedNetworkTools.oauthURL
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix(NetworkTools.sharedNetworkTools.redirectUri)
        {
            return true
        }

        if let query = request.URL?.query where query.hasPrefix("code=")  {
            
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            
            loadAccessToken(code)
        } else {
                close()
        }
        return false
    }
    
    private func loadAccessToken(code: String) {
        NetworkTools.sharedNetworkTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                self.netError()
                return
            }
            //1.用token获取信息创建用户账户模型
            //2.异步加载用户信息
            //3.保存用户信息(模型中完成) 
             UserAccount(dict: result!).loadUserInfo({ (error) -> () in
                if error != nil {
                    self.netError()
                    return
                }
                NSNotificationCenter.defaultCenter().postNotificationName(TurnToMainContoller, object: false)
                self.close()
            })
        }
     }
    //出现出错信息
    private func netError() {
        SVProgressHUD.showInfoWithStatus("网络不给力")
        //延时一段时间再关闭
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) {
            self.close()
        }
    
    }
}



